package service

import (
	"errors"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"
	"math/rand"
	"strconv"
	"vrcm/src/vrcm/app/admin/models/view"
	"vrcm/src/vrcm/app/admin/service/dto/view_manage"
	"vrcm/src/vrcm/common/apis"

	"vrcm/src/vrcm/common/actions"
	cDto "vrcm/src/vrcm/common/dto"
)

type ViewLimit struct {
	service.Service
}

// GetPage 获取ViewLimit列表
func (e *ViewLimit) GetPage(c *view_manage.ViewLimitGetPageReq, p *actions.DataPermission, list *[]view.ViewLimit, count *int64) error {
	var err error
	var data view.ViewLimit

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("ViewLimitService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取ViewLimit对象
func (e *ViewLimit) Get(d *view_manage.ViewLimitGetReq, model *view.ViewLimit) error {
	err := e.Orm.Where(map[string]interface{}{"bind_id": d.BindId, "is_delete": 2}).First(model).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		return nil
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

func (e *ViewLimit) GetWhiteUserByLimit(d *view_manage.GetWhiteUserByLimitReq, models *[]view.WhiteUser) error {
	err := e.Orm.Where(map[string]interface{}{"limit_id": d.LimitId}).Find(models).Error
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// GetByFilter 获取ViewLimit对象
func (e *ViewLimit) GetByFilter(d *view_manage.ViewLimitGetFilterReq, model *view.ViewLimit) error {
	err := e.Orm.Where(map[string]interface{}{"bind_id": d.BindId, "type": d.Type}).First(model).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		return nil
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// Insert 创建ViewLimit对象
func (e *ViewLimit) Insert(c *view_manage.ViewLimitInsertReq) error {
	var err error
	var data view.ViewLimit
	c.Generate(&data)
	tx := e.Orm.Begin()
	err = tx.Create(&data).Error
	if err != nil {
		e.Log.Errorf("ViewLimitService Insert error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	err = tx.Where(map[string]interface{}{"view_id": data.Id, "check_type": c.ViewCondition}).Delete(new(view.ViewCheck)).Error
	if err != nil {
		e.Log.Errorf("ViewCheckService Delete error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	v := view_manage.ViewCheckInsertReq{}
	v.ViewId = data.Id
	v.CreateBy = data.CreateBy
	v.CheckType = c.ViewCondition
	m := view.ViewCheck{}
	//v.Generate(&m)
	err = tx.Create(&m).Error
	if err != nil {
		e.Log.Errorf("ViewCheckService Insert error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	return nil
}

// Update 修改ViewLimit对象
func (e *ViewLimit) Update(c *view_manage.ViewLimitUpdateReq) error {
	var err error
	var data = view.ViewLimit{}
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err = tx.Error; err != nil {
		return err
	}

	tx.First(&data, c.GetId())
	c.Generate(&data)
	db := tx.Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("ViewLimitService Save error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	//先删除view_check关联信息
	//err = tx.Where(map[string]interface{}{"view_id": data.Id}).Delete(new(view.ViewCheck)).Error
	//if err != nil {
	//	e.Log.Errorf("ViewCheckService Delete error:%s \r\n", err)
	//	tx.Rollback()
	//	return err
	//}

	if len(c.LimitInfos) > 0 {
		v := view_manage.ViewCheckInsertReq{}
		v.ViewId = data.Id
		v.CreateBy = data.CreateBy
		v.CheckType = c.ViewCondition
		v.LimitInfos = c.LimitInfos
		m := make([]view.ViewCheck, 0, 10)
		v.Generate(&m)
		err = tx.Model(&view.ViewCheck{}).Save(&m).Error
		if err != nil {
			e.Log.Errorf("ViewCheckService insert error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		if db.RowsAffected == 0 {
			tx.Rollback()
			return errors.New("无数据更新")
		}
	}

	whiteUsers := make([]view.WhiteUser, 0, 5)
	for _, user := range c.WhiteUsers {
		whiteUser := view.WhiteUser{}
		whiteUser.TenantId = c.TenantId
		whiteUser.UserId = user.UserId
		whiteUser.LimitId = data.Id
		whiteUser.UserName = user.UserName
		whiteUser.PhoneOrEmail = user.PhoneOrEmail
		whiteUsers = append(whiteUsers, whiteUser)
	}
	if len(whiteUsers) > 0 {
		err = tx.Save(&whiteUsers).Error
		if err != nil {
			e.Log.Errorf("WhiteUser save error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	tx.Commit()
	return nil
}

// Remove 删除ViewLimit
func (e *ViewLimit) Remove(d *view_manage.ViewLimitDeleteReq, p *actions.DataPermission) error {
	var data view.ViewLimit

	db := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).Delete(&data, d.GetId())
	if err := db.Error; err != nil {
		e.Log.Errorf("Service RemoveViewLimit error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

// GenerateViewCode 生成观看码
func (e *ViewLimit) GenerateViewCode(d *view_manage.GenerateViewCodeReq) []view_manage.LimitInfo {
	data := make([]view_manage.LimitInfo, 0, 10)
	// 随机生成验证码
	for i := 0; i < d.PaperNum; i++ {
		random := apis.ProcessRandomObject(rand.Uint64())
		limitInfo := view_manage.LimitInfo{
			LimitInfo: random,
			IsSms:     2,
		}
		data = append(data, limitInfo)
	}

	return data
}

func (e *ViewLimit) SaveWhiteUser(c *view_manage.SaveWhiteUserReq) error {

	whiteUsers := make([]view.WhiteUser, 0, 5)
	for _, user := range c.WhiteUsers {
		whiteUser := view.WhiteUser{}
		whiteUser.Id = user.Id
		whiteUser.TenantId = c.TenantId
		whiteUser.UserId = user.UserId
		whiteUser.LimitId = c.LimitId
		whiteUser.UserName = user.UserName
		whiteUser.PhoneOrEmail = user.PhoneOrEmail
		whiteUsers = append(whiteUsers, whiteUser)
	}
	e.Log.Trace("WhiteUser:", whiteUsers)
	if len(whiteUsers) > 0 {
		err := e.Orm.Save(&whiteUsers).Error
		if err != nil {
			e.Log.Errorf("WhiteUser save error:%s \r\n", err)
			return err
		}
	}
	return nil
}

func (e *ViewLimit) DeleteWhiteUser(c *view_manage.DeleteWhiteUserReq) error {

	err := e.Orm.Model(&view.WhiteUser{}).Where("id in ?", c.Ids).Delete(&view.WhiteUser{}).Error
	if err != nil {
		e.Log.Errorf("WhiteUser delete error:%s \r\n", err)
		return err
	}
	return nil
}

func (e *ViewLimit) GetWhiteUser(c *view_manage.GetWhiteUserReq) (view.WhiteUser, error) {

	white := view.WhiteUser{}
	err := e.Orm.Model(&view.WhiteUser{}).Where("id = ?", c.Id).Find(&white).Error
	if err != nil {
		e.Log.Errorf("WhiteUser get error:%s \r\n", err)
		return white, err
	}
	return white, nil
}

func (e *ViewLimit) CheckWhiteUser(c *view_manage.CheckWhiteUserReq) (bool, error) {

	isOK := false
	whites := make([]view.WhiteUser, 0, 5)
	viewLimit := view.ViewLimit{}
	bindId := strconv.Itoa(c.LiveId)
	err := e.Orm.Model(&view.ViewLimit{}).Where("bind_id = ?", bindId).Find(&viewLimit).Error
	if err != nil {
		e.Log.Errorf("ViewLimit get error:%s \r\n", err)
		return isOK, err
	}

	err = e.Orm.Model(&view.WhiteUser{}).Where("limit_id = ?", viewLimit.Id).Find(&whites).Error
	if err != nil {
		e.Log.Errorf("WhiteUser get error:%s \r\n", err)
		return isOK, err
	}

	for _, white := range whites {
		if white.PhoneOrEmail == c.UserName {
			isOK = true
			break
		}
		if white.UserName == c.UserName {
			isOK = true
			break
		}
	}
	return isOK, nil
}
